package com.duan.luren.simpleQueue;

import com.duan.luren.ConnectionHelper;
import com.rabbitmq.client.*;

import java.io.IOException;

import static com.duan.luren.simpleQueue.SimpleQueueProducer.QueueName;

/**
 * 简单队列消费消息
 */
public class SimpleQueueConsumer {
    //定义队列的名称

    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionHelper.getConnection();
        Channel channel = connection.createChannel();

        // 队列名，是否实例化，是否独占，是否自动删除，
        channel.queueDeclare(QueueName, false, false, false, null);
//        channel.basicQos(1);// 设置预取数量1
        // 定义一个回调函数来处理接收到的消息
//        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
//            String message = new String(delivery.getBody(), "UTF-8");
//            System.out.println(" [x] Received '" + message + "'");
//        };
//        channel.basicConsume(QueueName, true, deliverCallback, consumerTag -> {
//        });


        Consumer myconsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("========================");
                System.out.println("routingKey: " + envelope.getRoutingKey());
                System.out.println("contentType: " + properties.getContentType());
                System.out.println("deliveryTag: " + envelope.getDeliveryTag());
                System.out.println("content: " + new String(body, "UTF-8"));
                try {
                    Thread.sleep(50000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("休眠结束");
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };

        // 第二个参数  true 自动ack；false，手动ack。手动ack就需要
        channel.basicConsume(QueueName, false, myconsumer);

    }
}
